"""
任务相关路由
"""
from flask import request
from flask_restful import Resource
from ..utils.helpers import success_response, error_response, handle_errors
from ..utils.flowable_client import FlowableClient
try:
    from server.config.config import Config  # type: ignore
except ModuleNotFoundError:
    from config.config import Config  # type: ignore


class TaskListResource(Resource):
    """任务列表资源"""
    
    def __init__(self):
        self.flowable_client = FlowableClient(
            Config.FLOWABLE_REST_URL,
            Config.FLOWABLE_REST_USER,
            Config.FLOWABLE_REST_PASSWORD
        )
    
    @handle_errors
    def get(self):
        """查询待办任务列表"""
        assignee = request.args.get('assignee')
        candidate_group = request.args.get('candidate_group')
        process_instance_id = request.args.get('process_instance_id')
        
        tasks = self.flowable_client.get_tasks(
            assignee=assignee,
            candidate_group=candidate_group,
            process_instance_id=process_instance_id
        )
        
        return success_response(tasks)


class TaskApprovalResource(Resource):
    """任务审批资源"""
    
    def __init__(self):
        self.flowable_client = FlowableClient(
            Config.FLOWABLE_REST_URL,
            Config.FLOWABLE_REST_USER,
            Config.FLOWABLE_REST_PASSWORD
        )
    
    @handle_errors
    def post(self, task_id):
        """完成任务（审批）"""
        data = request.get_json()
        
        # 验证必填字段
        if 'approvalResult' not in data:
            return error_response('缺少审批结果', 400)
        
        # 完成任务
        variables = {
            'approvalResult': data['approvalResult'],
            'approvalComment': data.get('approvalComment', '')
        }
        
        self.flowable_client.complete_task(task_id, variables)
        
        return success_response(None, '审批完成')


class TaskDetailResource(Resource):
    """任务详情资源"""
    
    def __init__(self):
        self.flowable_client = FlowableClient(
            Config.FLOWABLE_REST_URL,
            Config.FLOWABLE_REST_USER,
            Config.FLOWABLE_REST_PASSWORD
        )
    
    @handle_errors
    def get(self, task_id):
        """获取任务变量"""
        variables = self.flowable_client.get_task_variables(task_id)
        return success_response(variables)
